"""
数据分析API视图
"""
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from django.db.models import Count, Avg, Q, Max, Min
from apps.positions.models import Position
from utils.response import success_response, error_response
from utils.keyword_extract import extract_skills_from_job_descriptions


class OverviewView(APIView):
    """数据概览API"""
    
    def get(self, request):
        """
        获取数据概览统计
        
        Returns:
            {
                'total_positions': int,  # 总职位数
                'total_companies': int,   # 总公司数
                'avg_salary': float,      # 平均薪资
                'total_cities': int       # 城市数量
            }
        """
        total_positions = Position.objects.count()
        total_companies = Position.objects.values('company_id').distinct().count()
        avg_salary = Position.objects.filter(salary_avg__isnull=False).aggregate(Avg('salary_avg'))['salary_avg__avg']
        total_cities = Position.objects.values('city').distinct().count()
        
        data = {
            'total_positions': total_positions,
            'total_companies': total_companies,
            'avg_salary': round(float(avg_salary), 2) if avg_salary else 0,
            'total_cities': total_cities
        }
        
        return success_response(data=data, message='获取数据概览成功')


class CompanyStatsView(APIView):
    """公司统计API"""
    
    def get(self, request):
        """
        公司规模和融资阶段统计
        
        Returns:
            {
                'company_size_distribution': [...],
                'finance_stage_distribution': [...]
            }
        """
        # 公司规模分布
        company_size_dist = Position.objects.values('company_size').annotate(
            count=Count('id')
        ).filter(company_size__isnull=False).order_by('-count')
        
        # 融资阶段分布
        finance_stage_dist = Position.objects.values('finance_stage').annotate(
            count=Count('id')
        ).filter(finance_stage__isnull=False).order_by('-count')
        
        data = {
            'company_size_distribution': list(company_size_dist),
            'finance_stage_distribution': list(finance_stage_dist)
        }
        
        return success_response(data=data, message='获取公司统计成功')


class PositionDistributionView(APIView):
    """职位分布API"""
    
    def get(self, request):
        """
        职位类别分布（Top 20）
        
        Returns:
            {
                'category_distribution': [...],
                'big_category_distribution': [...]
            }
        """
        # 细分类别分布
        category_dist = Position.objects.values('category').annotate(
            count=Count('id')
        ).filter(category__isnull=False).order_by('-count')[:20]
        
        # 大类分布
        big_category_dist = Position.objects.values('big_category').annotate(
            count=Count('id')
        ).filter(big_category__isnull=False).order_by('-count')
        
        data = {
            'category_distribution': list(category_dist),
            'big_category_distribution': list(big_category_dist)
        }
        
        return success_response(data=data, message='获取职位分布成功')


class CityDistributionView(APIView):
    """城市分布API"""
    
    def get(self, request):
        """
        城市职位分布
        
        Returns:
            {
                'city_distribution': [
                    {'city': 'Beijing', 'count': 1234, 'avg_salary': 25.6},
                    ...
                ]
            }
        """
        city_dist = Position.objects.values('city').annotate(
            count=Count('id'),
            avg_salary=Avg('salary_avg')
        ).filter(city__isnull=False).order_by('-count')
        
        # 格式化数据
        data = {
            'city_distribution': [
                {
                    'city': item['city'],
                    'count': item['count'],
                    'avg_salary': round(float(item['avg_salary']), 2) if item['avg_salary'] else 0
                }
                for item in city_dist
            ]
        }
        
        return success_response(data=data, message='获取城市分布成功')


class SalaryByExperienceView(APIView):
    """薪资与经验关系API"""
    
    def get(self, request):
        """
        薪资与工作经验关系分析
        
        Returns:
            {
                'data': [
                    {'work_year': '1-3年', 'count': 123, 'avg_salary': 18.5, 'min_salary': 5, 'max_salary': 50},
                    ...
                ]
            }
        """
        salary_experience = Position.objects.values('work_year').annotate(
            count=Count('id'),
            avg_salary=Avg('salary_avg'),
            min_salary=Min('salary_min'),
            max_salary=Max('salary_max')
        ).filter(work_year__isnull=False, salary_avg__isnull=False).order_by('work_year')
        
        data = {
            'data': [
                {
                    'work_year': item['work_year'],
                    'count': item['count'],
                    'avg_salary': round(float(item['avg_salary']), 2) if item['avg_salary'] else 0,
                    'min_salary': round(float(item['min_salary']), 2) if item['min_salary'] else 0,
                    'max_salary': round(float(item['max_salary']), 2) if item['max_salary'] else 0
                }
                for item in salary_experience
            ]
        }
        
        return success_response(data=data, message='获取薪资与经验关系成功')


class SalaryByEducationView(APIView):
    """薪资与学历关系API"""
    
    def get(self, request):
        """
        薪资与学历关系分析
        
        Returns:
            {
                'data': [
                    {'education': '本科', 'count': 123, 'avg_salary': 20.5},
                    ...
                ]
            }
        """
        salary_education = Position.objects.values('education').annotate(
            count=Count('id'),
            avg_salary=Avg('salary_avg')
        ).filter(education__isnull=False, salary_avg__isnull=False).order_by('-avg_salary')
        
        data = {
            'data': [
                {
                    'education': item['education'],
                    'count': item['count'],
                    'avg_salary': round(float(item['avg_salary']), 2) if item['avg_salary'] else 0
                }
                for item in salary_education
            ]
        }
        
        return success_response(data=data, message='获取薪资与学历关系成功')


class SalaryByCityView(APIView):
    """薪资与城市关系API"""
    
    def get(self, request):
        """
        不同城市的薪资水平（Top 20）
        
        Returns:
            {
                'data': [
                    {'city': 'Beijing', 'count': 1234, 'avg_salary': 28.5},
                    ...
                ]
            }
        """
        salary_city = Position.objects.values('city').annotate(
            count=Count('id'),
            avg_salary=Avg('salary_avg')
        ).filter(city__isnull=False, salary_avg__isnull=False).order_by('-avg_salary')[:20]
        
        data = {
            'data': [
                {
                    'city': item['city'],
                    'count': item['count'],
                    'avg_salary': round(float(item['avg_salary']), 2) if item['avg_salary'] else 0
                }
                for item in salary_city
            ]
        }
        
        return success_response(data=data, message='获取薪资与城市关系成功')


@api_view(['GET'])
def job_profile(request, category):
    """
    岗位画像API
    
    Args:
        category: 职位类别
    
    Returns:
        {
            'basic_info': {...},
            'salary_distribution': {...},
            'education_distribution': [...],
            'experience_distribution': [...],
            'keywords': [...]
        }
    """
    # 基本信息
    positions = Position.objects.filter(category=category)
    total_count = positions.count()
    
    if total_count == 0:
        return error_response(message=f'未找到{category}相关职位', code=404)
    
    # 薪资统计
    salary_stats = positions.filter(salary_avg__isnull=False).aggregate(
        avg_salary=Avg('salary_avg'),
        min_salary=Min('salary_min'),
        max_salary=Max('salary_max')
    )
    
    # 学历分布
    education_dist = positions.values('education').annotate(
        count=Count('id')
    ).filter(education__isnull=False).order_by('-count')
    
    # 经验分布
    experience_dist = positions.values('work_year').annotate(
        count=Count('id')
    ).filter(work_year__isnull=False).order_by('-count')
    
    # 关键词提取（从职位描述中）
    descriptions = positions.filter(position_detail__isnull=False).values_list('position_detail', flat=True)[:100]
    keywords = extract_skills_from_job_descriptions(list(descriptions), top_k=50)
    
    data = {
        'basic_info': {
            'total_count': total_count,
            'avg_salary': round(float(salary_stats['avg_salary']), 2) if salary_stats['avg_salary'] else 0,
            'min_salary': round(float(salary_stats['min_salary']), 2) if salary_stats['min_salary'] else 0,
            'max_salary': round(float(salary_stats['max_salary']), 2) if salary_stats['max_salary'] else 0
        },
        'education_distribution': list(education_dist),
        'experience_distribution': list(experience_dist),
        'keywords': keywords['keywords'][:50]
    }
    
    return success_response(data=data, message=f'获取{category}岗位画像成功')

